import {ApiCall} from "tsrpc";
import {ReqGet, ResGet} from "../../shared/protocols/teams/PtlGet";
import {Global} from "../../mongodb";

export default async function (call: ApiCall<ReqGet, ResGet>) {
    try {
        const { pageIndex, pageSize, name } = call.req.query;
        console.info("执行到这里")
        const filter: any = {};
        if (name) {
            filter.name = new RegExp(name, 'i'); // 'i'标志表示不区分大小写
        }
        // 执行聚合查询，这里简化为直接查找所有文档，无需特定的pipeline
        const ret = await Global.db.collection('teams').aggregate([
            {
                $match: filter
            },
            {
                $facet: {
                    total: [{$count: 'total'}],
                    data: [{$sort: {_id: -1}}, {$skip: (pageIndex - 1) * pageSize}, {$limit: pageSize}],
                },
            },
        ]).toArray();
        console.info("z制剂室:",ret)
        return call.succ({
            data: ret[0].data,
            pageTotal: ret[0].total[0]?.total || 0
        });
    } catch (error) {
        console.error("Error occurred during fetching teams:", error);
    }
}
